<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="C#,WebBrowser,TCP服务器,JAVA客户端,WinIO,模拟按键,浏览器,表单自动录入,模拟登录," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="很久没有用C#写过代码了，有些生疏，因项目需要，又没有人手，所以只好赤膊上阵。这次把思路和要点记录下来，供以后参考。项目的大体思路是：JAVA客户端向C#服务器端传递指令，C#服务器接收到指令后打开浏览器，提交页面信息并将返回的页面数据传递给JAVA客户端，这一切自动进行不允许人工干预。">
<meta property="og:type" content="article">
<meta property="og:title" content="C#模拟浏览器并与JAVA交互">
<meta property="og:url" content="http://chrisrc.me/2015/10/18/csharp-with-java/index.html">
<meta property="og:site_name" content="山中，山外与俯瞰">
<meta property="og:description" content="很久没有用C#写过代码了，有些生疏，因项目需要，又没有人手，所以只好赤膊上阵。这次把思路和要点记录下来，供以后参考。项目的大体思路是：JAVA客户端向C#服务器端传递指令，C#服务器接收到指令后打开浏览器，提交页面信息并将返回的页面数据传递给JAVA客户端，这一切自动进行不允许人工干预。">
<meta property="og:updated_time" content="2016-12-17T07:29:29.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="C#模拟浏览器并与JAVA交互">
<meta name="twitter:description" content="很久没有用C#写过代码了，有些生疏，因项目需要，又没有人手，所以只好赤膊上阵。这次把思路和要点记录下来，供以后参考。项目的大体思路是：JAVA客户端向C#服务器端传递指令，C#服务器接收到指令后打开浏览器，提交页面信息并将返回的页面数据传递给JAVA客户端，这一切自动进行不允许人工干预。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://chrisrc.me/2015/10/18/csharp-with-java/"/>





  <title> C#模拟浏览器并与JAVA交互 | 山中，山外与俯瞰 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">山中，山外与俯瞰</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">一次永不停止的探索之旅</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-dcos">
          <a href="/dcos" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            DC/OS
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="st-search-show-outputs">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <form class="site-search-form">
  <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>

<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install', 'R9GcmhBwxpsAGLNCsquZ','2.0.0');
</script>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://chrisrc.me/2015/10/18/csharp-with-java/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="chrisrc">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/images/avatar.gif">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="山中，山外与俯瞰">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="山中，山外与俯瞰" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                C#模拟浏览器并与JAVA交互
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2015-10-18T14:12:21+08:00">
                2015-10-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Snippets/" itemprop="url" rel="index">
                    <span itemprop="name">Snippets</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <a href="/2015/10/18/csharp-with-java/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2015/10/18/csharp-with-java/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>很久没有用C#写过代码了，有些生疏，因项目需要，又没有人手，所以只好赤膊上阵。这次把思路和要点记录下来，供以后参考。项目的大体思路是：JAVA<br>客户端向C#服务器端传递指令，C#服务器接收到指令后打开浏览器，提交页面信息并将返回的页面数据传递给JAVA客户端，这一切自动进行不允许人工<br>干预。</p>
<a id="more"></a>
<h2 id="C-服务器与JAVA客户端通信"><a href="#C-服务器与JAVA客户端通信" class="headerlink" title="C#服务器与JAVA客户端通信"></a>C#服务器与JAVA客户端通信</h2><p>.NET4.5之后有HTTP服务器的内部实现，但受限于运行环境，只能采用4.0框架以下版本，所以JAVA客户端与C#服务器之间的交互协议采用TCP/IP。</p>
<h3 id="协议指令定义"><a href="#协议指令定义" class="headerlink" title="协议指令定义"></a>协议指令定义</h3><p>TCP协议传输的包是无应用边界的，只能在协议之上定义自己的交互语义。TCP/IP之上定义交互语义的方式有多种，这里采用老办法以4字节长度界定数据<br>报文。</p>
<h3 id="客户端向服务器发送报文"><a href="#客户端向服务器发送报文" class="headerlink" title="客户端向服务器发送报文"></a>客户端向服务器发送报文</h3><p>JAVA客户端向C#服务器首先发送4个字节，这4个字节是后续指令数据的字节长度。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">string cmd = <span class="string">""</span>;</div><div class="line"><span class="keyword">byte</span>[] lenBytes = toByteArray(cmd.getBytes().length);</div><div class="line"><span class="keyword">byte</span>[] cmdBytes = cmd.getBytes();</div><div class="line"><span class="keyword">byte</span>[] all = <span class="keyword">new</span> <span class="keyword">byte</span>[lenBytes.length + cmdBytes.length];</div><div class="line">System.arraycopy(lenBytes, <span class="number">0</span>, all, <span class="number">0</span>, lenBytes.length);</div><div class="line">System.arraycopy(cmdBytes, <span class="number">0</span>, all, lenBytes.length, cmdBytes.length);</div><div class="line">out.write(all);</div><div class="line">out.flush();</div></pre></td></tr></table></figure>
<h3 id="服务器接收数据报文"><a href="#服务器接收数据报文" class="headerlink" title="服务器接收数据报文"></a>服务器接收数据报文</h3><p>C#服务器接收到数据后根据前4个字节确定指令数据的长度。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line">protected byte[] readStream(TcpClient client)</div><div class="line">&#123;</div><div class="line">    NetworkStream stream = client.GetStream();</div><div class="line">    if (stream.DataAvailable)</div><div class="line">    &#123;</div><div class="line">        byte[] data = new byte[client.Available];</div><div class="line">        int bytesRead = 0;</div><div class="line">        try</div><div class="line">        &#123;</div><div class="line">            bytesRead = stream.Read(data, 0, data.Length);</div><div class="line">        &#125;</div><div class="line">        catch (IOException)</div><div class="line">        &#123;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        if (bytesRead &lt; data.Length)</div><div class="line">        &#123;</div><div class="line">            byte[] lastData = data;</div><div class="line">            data = new byte[bytesRead];</div><div class="line">            Array.ConstrainedCopy(lastData, 4, data, 0, bytesRead - 4);</div><div class="line">        &#125;</div><div class="line">        else</div><div class="line">        &#123;</div><div class="line">            byte[] lastData = data;</div><div class="line">            data = new byte[data.Length];</div><div class="line">            Array.ConstrainedCopy(lastData, 4, data, 0, data.Length - 4);</div><div class="line">        &#125;</div><div class="line">        return data;</div><div class="line">    &#125;</div><div class="line">    return null;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>注：</strong> 上述代码直接抛弃了对数据长度的处理，仅在JAVA端一次调用<code>write</code>方法发送数据时才能正确处理。TCP包数量受发送缓冲区和接收缓冲区大小<br>影响，生产环境需要重新考虑。</p>
<h3 id="服务器解析处理数据"><a href="#服务器解析处理数据" class="headerlink" title="服务器解析处理数据"></a>服务器解析处理数据</h3><p>C#服务器获取数据后解析指令进行处理。因TCP Server运行在UI主线程之中，在数据处理过程中需要创建新的窗口，所以需要通过<code>Delegate</code>处理数据。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">public delegate void invokeDelegate();</div><div class="line">byte[] data = readStream(connection.Socket);</div><div class="line">if (data != null)</div><div class="line">&#123;</div><div class="line">    string dataStr = Encoding.UTF8.GetString(data);</div><div class="line">    invokeDelegate del = () =&gt;</div><div class="line">    &#123;</div><div class="line">        processData(dataStr.TrimEnd(eofChars), connection.Socket);</div><div class="line">        logData(false, dataStr);</div><div class="line">    &#125;;</div><div class="line">    Invoke(del);</div><div class="line">    data = null;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="服务器返回结果报文给客户端"><a href="#服务器返回结果报文给客户端" class="headerlink" title="服务器返回结果报文给客户端"></a>服务器返回结果报文给客户端</h3><p>C#服务器组织结果数据，返回给JAVA客户端。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">using (BinaryWriter sw = new BinaryWriter(currentStream))</div><div class="line">&#123;</div><div class="line">    string data = &quot;&quot;;</div><div class="line">    byte[] data = Utils.GetBytes(data);</div><div class="line">    byte[] cmdBytes = Utils.Get8BitBytes(currentCmd);</div><div class="line">    sw.Write(BitConverter.GetBytes(cmdBytes.Length + data.Length));</div><div class="line">    sw.Write(cmdBytes);</div><div class="line">    sw.Write(data);</div><div class="line">    sw.Flush();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="客户端处理返回的结果数据"><a href="#客户端处理返回的结果数据" class="headerlink" title="客户端处理返回的结果数据"></a>客户端处理返回的结果数据</h3><p>JAVA客户端接收服务器的返回结果数据，解析并处理。因C#与JAVA对<code>int</code>数据转换得到的字节数组的高低位相反，因此需要特殊处理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">byte</span>[] lenBuf = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">4</span>];</div><div class="line">input.readFully(lenBuf);</div><div class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">2</span>; i++) &#123;</div><div class="line">    <span class="keyword">byte</span> tmp = lenBuf[i];</div><div class="line">    lenBuf[i] = lenBuf[<span class="number">4</span> - i - <span class="number">1</span>];</div><div class="line">    lenBuf[<span class="number">4</span> - i - <span class="number">1</span>] = tmp;</div><div class="line">&#125;</div><div class="line"><span class="keyword">int</span> length = ByteBuffer.wrap(lenBuf).getInt();</div></pre></td></tr></table></figure>
<p>获得服务返回的数据长度后，根据长度等待读取数据：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">int</span> len = <span class="number">0</span>;</div><div class="line"><span class="keyword">byte</span>[] data = <span class="keyword">new</span> <span class="keyword">byte</span>[length];</div><div class="line"><span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">256</span>];</div><div class="line"><span class="keyword">while</span> (len &lt; length) &#123;</div><div class="line">    <span class="keyword">int</span> count = input.read(buffer);</div><div class="line">    System.arraycopy(buffer, <span class="number">0</span>, data, len, count);</div><div class="line">    len += count;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="指令队列"><a href="#指令队列" class="headerlink" title="指令队列"></a>指令队列</h2><h3 id="生产者消费者模式"><a href="#生产者消费者模式" class="headerlink" title="生产者消费者模式"></a>生产者消费者模式</h3><p>服务器接收到指令数据解析为业务指令后，将指令数据放入队列。消费者线程从队列中获取指令进行业务处理。</p>
<h3 id="指令的处理"><a href="#指令的处理" class="headerlink" title="指令的处理"></a>指令的处理</h3><p>部分指令可以并行处理，但存在某种指令在执行时需要独占图形视窗，此时其他视窗指令不能执行，必须等待。因此构建一个全局<code>AutoResetEvent</code><br>执行特定指令时，消费者线程进入等待状态，当特定指令线程执行完毕，通知消费者线程结束等待，开始执行。</p>
<h2 id="C-WebBrowser"><a href="#C-WebBrowser" class="headerlink" title="C# WebBrowser"></a>C# WebBrowser</h2><h3 id="获取Form表单，填写输入项"><a href="#获取Form表单，填写输入项" class="headerlink" title="获取Form表单，填写输入项"></a>获取<code>Form</code>表单，填写输入项</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">HtmlDocument doc = this.icbcWebBrowser.Document;</div><div class="line">HtmlDocument doc = this.icbcWebBrowser.Document.Window.Frames[&quot;frame&quot;].Document;</div><div class="line">HtmlElementCollection hec = doc.Forms.GetElementsByName(&quot;form&quot;);</div><div class="line">// USER</div><div class="line">HtmlElement user = hec[0].Document.GetElementById(&quot;user&quot;);</div><div class="line">if (user != null)</div><div class="line">user.SetAttribute(&quot;value&quot;, &quot;user&quot;);</div><div class="line">// Image</div><div class="line">HtmlDocument ccDoc = (HtmlDocument)hec[0].Document.Window.Frames[1].Document;</div><div class="line">HtmlElementCollection imgs = ccDoc.GetElementsByTagName(&quot;img&quot;);</div></pre></td></tr></table></figure>
<h3 id="提交表单"><a href="#提交表单" class="headerlink" title="提交表单"></a>提交表单</h3><p>提交表单的方法有多种，可以直接获取控件，调用控件对象的<code>InvokeMember(&quot;click&quot;)</code>方法，也可以执行<code>JavaScript</code>脚本。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">Task.Factory.StartNew(()=&gt; &#123;</div><div class="line">    waitPassCompleted.WaitOne();</div><div class="line"></div><div class="line">    Thread.Sleep(2000);</div><div class="line">    Action submit = () =&gt; &#123;</div><div class="line"></div><div class="line">        this.abcBankWebBrowser.Document.InvokeScript(&quot;eval&quot;, new object[] &#123; &quot; document.getElementById(&apos;submitButton&apos;).getElementsByTagName(&apos;a&apos;)[4].click(); &quot; &#125;);</div><div class="line">    &#125;;</div><div class="line">    this.BeginInvoke(submit);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<h2 id="WinIO"><a href="#WinIO" class="headerlink" title="WinIO"></a>WinIO</h2><p>下载<a href="http://www.internals.com/utilities/WinIo.zip" target="_blank" rel="external">WinIO</a>,解压后，将<code>WinIo64.sys</code>的签名（测试签名）添加到系统中。以系统管理员身份<br>执行下面的指令打开系统测试模式，允许加载测试签名。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">bcdedit -set loadoptions DDISABLE_INTEGRITY_CHECKS</div><div class="line"></div><div class="line">bcdedit -set testsigning ON</div></pre></td></tr></table></figure>
<p>重新启动系统，检查是否能够正确加载WinIO驱动。</p>
<p><strong>现象</strong>：在笔记本电脑上运行良好，在台式机上，如果键盘为USB，正确加载但无效果。换成PS2键盘，有效果但不稳定（待进一步验证）。</p>
<h2 id="工具代码"><a href="#工具代码" class="headerlink" title="工具代码"></a>工具代码</h2><h3 id="JAVA-int型与byte-array的相互转换"><a href="#JAVA-int型与byte-array的相互转换" class="headerlink" title="JAVA int型与byte array的相互转换"></a>JAVA int型与byte array的相互转换</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">static</span> <span class="keyword">byte</span>[] toByteArray(<span class="keyword">int</span> value) &#123;</div><div class="line">    <span class="keyword">return</span> ByteBuffer.allocate(<span class="number">4</span>).putInt(value).array();</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">fromByteArray</span><span class="params">(<span class="keyword">byte</span>[] bytes)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> ByteBuffer.wrap(bytes).getInt();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="获取浏览器Cookie"><a href="#获取浏览器Cookie" class="headerlink" title="获取浏览器Cookie"></a>获取浏览器Cookie</h3><p>通过C# WebBrowser的<code>Document</code>对象可以直接获取Cookie，但有时候因为安全原因，只能获取部分Cookie,要想获取全部Cookie,可通过如下<br>代码获取：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">[DllImport(&quot;wininet.dll&quot;, CharSet = CharSet.Auto, SetLastError = true)]</div><div class="line">static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);</div><div class="line">const int INTERNET_COOKIE_HTTPONLY = 0x00002000;</div><div class="line">public static string GetGlobalCookies(string uri)</div><div class="line">&#123;</div><div class="line">    uint datasize = 1024;</div><div class="line">    StringBuilder cookieData = new StringBuilder((int)datasize);</div><div class="line">    if (InternetGetCookieEx(uri, null, cookieData, ref datasize, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero)</div><div class="line">    &amp;&amp; cookieData.Length &gt; 0)</div><div class="line">    &#123;</div><div class="line">        return cookieData.ToString().Trim();</div><div class="line">    &#125;</div><div class="line">    else</div><div class="line">    &#123;</div><div class="line">        return null;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="获取HTML中的img图像"><a href="#获取HTML中的img图像" class="headerlink" title="获取HTML中的img图像"></a>获取HTML中的img图像</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line">public static Image GetRegCodePic(WebBrowser wbMail, string ImgName, string Src, string Alt)</div><div class="line">&#123;</div><div class="line">    HTMLDocument doc = (HTMLDocument)wbMail.Document.DomDocument;</div><div class="line">    HTMLBody body = (HTMLBody)doc.body;</div><div class="line">    IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange();</div><div class="line">    IHTMLControlElement Img;</div><div class="line">    if (ImgName == &quot;&quot;) //如果没有图片的名字,通过Src或Alt中的关键字来取</div><div class="line">    &#123;</div><div class="line">        int ImgNum = GetPicIndex(wbMail, Src, Alt);</div><div class="line">        if (ImgNum == -1) return null;</div><div class="line">        Img = (IHTMLControlElement)wbMail.Document.Images[ImgNum].DomElement;</div><div class="line">    &#125;</div><div class="line">    else</div><div class="line">        Img = (IHTMLControlElement)wbMail.Document.All[ImgName].DomElement;</div><div class="line"></div><div class="line">    //rang.execCommand(&quot;Unselect&quot;);</div><div class="line">    rang.add(Img);</div><div class="line">    rang.execCommand(&quot;Copy&quot;, false, null);</div><div class="line">    Image RegImg = Clipboard.GetImage();</div><div class="line">    Clipboard.Clear();</div><div class="line"></div><div class="line">    return RegImg;</div><div class="line">&#125;</div><div class="line"></div><div class="line">public static int GetPicIndex(WebBrowser wbMail, string Src, string Alt)</div><div class="line">&#123;</div><div class="line">    int imgnum = -1;</div><div class="line">    for (int i = 0; i &lt; wbMail.Document.Images.Count; i++) //获取所有的Image元素</div><div class="line">    &#123;</div><div class="line">        IHTMLImgElement img = (IHTMLImgElement)wbMail.Document.Images[i].DomElement;</div><div class="line">        if (Alt == &quot;&quot;)</div><div class="line">        &#123;</div><div class="line">            if (img.src.Contains(Src)) return i;</div><div class="line">        &#125;</div><div class="line">        else</div><div class="line">        &#123;</div><div class="line">            if (!string.IsNullOrEmpty(img.alt))</div><div class="line">            &#123;</div><div class="line">                if (img.alt.Contains(Alt)) return i;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    return imgnum;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="C-中字符串和字节数组的转换"><a href="#C-中字符串和字节数组的转换" class="headerlink" title="C#中字符串和字节数组的转换"></a>C#中字符串和字节数组的转换</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line">public static byte[] GetBytes(string str)</div><div class="line">&#123;</div><div class="line">    byte[] bytes = new byte[str.Length * sizeof(char)];</div><div class="line">    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);</div><div class="line">    return bytes;</div><div class="line">&#125;</div><div class="line"></div><div class="line">public static string GetString(byte[] bytes)</div><div class="line">&#123;</div><div class="line">    char[] chars = new char[bytes.Length / sizeof(char)];</div><div class="line">    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);</div><div class="line">    return new string(chars);</div><div class="line">&#125;</div><div class="line"></div><div class="line">public static byte[] Get8BitBytes(string str)</div><div class="line">&#123;</div><div class="line">    char[] chars = str.ToCharArray();</div><div class="line">    byte[] data = new byte[chars.Length];</div><div class="line">    for (int i = 0; i &lt; chars.Length; i++)</div><div class="line">    &#123;</div><div class="line">        data[i] = (byte)chars[i];</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    return data;</div><div class="line">&#125;</div></pre></td></tr></table></figure>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/C/" rel="tag"># C#</a>
          
            <a href="/tags/WebBrowser/" rel="tag"># WebBrowser</a>
          
            <a href="/tags/TCP服务器/" rel="tag"># TCP服务器</a>
          
            <a href="/tags/JAVA客户端/" rel="tag"># JAVA客户端</a>
          
            <a href="/tags/WinIO/" rel="tag"># WinIO</a>
          
            <a href="/tags/模拟按键/" rel="tag"># 模拟按键</a>
          
            <a href="/tags/浏览器/" rel="tag"># 浏览器</a>
          
            <a href="/tags/表单自动录入/" rel="tag"># 表单自动录入</a>
          
            <a href="/tags/模拟登录/" rel="tag"># 模拟登录</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2015/10/04/essays-living-in-the-age-of-software-fuckery/" rel="next" title="生活进入'软件笨蛋'时代">
                <i class="fa fa-chevron-left"></i> 生活进入'软件笨蛋'时代
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2015/11/15/autoit-cluster-dev-on-vagrant-with-ansible/" rel="prev" title="Vagrant+VirtualBox+Ansible在Windows系统上自动化搭建集群开发环境">
                Vagrant+VirtualBox+Ansible在Windows系统上自动化搭建集群开发环境 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <div class="ds-share flat" data-thread-key="2015/10/18/csharp-with-java/"
     data-title="C#模拟浏览器并与JAVA交互"
     data-content=""
     data-url="http://chrisrc.me/2015/10/18/csharp-with-java/">
  <div class="ds-share-inline">
    <ul  class="ds-share-icons-16">

      <li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
      <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
      <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
      <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
      <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>

    </ul>
    <div class="ds-share-icons-more">
    </div>
  </div>
</div>
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2015/10/18/csharp-with-java/"
           data-title="C#模拟浏览器并与JAVA交互" data-url="http://chrisrc.me/2015/10/18/csharp-with-java/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="chrisrc" />
          <p class="site-author-name" itemprop="name">chrisrc</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">69</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">21</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">162</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/christtrc" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/chrisrc" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#C-服务器与JAVA客户端通信"><span class="nav-number">1.</span> <span class="nav-text">C#服务器与JAVA客户端通信</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#协议指令定义"><span class="nav-number">1.1.</span> <span class="nav-text">协议指令定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端向服务器发送报文"><span class="nav-number">1.2.</span> <span class="nav-text">客户端向服务器发送报文</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务器接收数据报文"><span class="nav-number">1.3.</span> <span class="nav-text">服务器接收数据报文</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务器解析处理数据"><span class="nav-number">1.4.</span> <span class="nav-text">服务器解析处理数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务器返回结果报文给客户端"><span class="nav-number">1.5.</span> <span class="nav-text">服务器返回结果报文给客户端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端处理返回的结果数据"><span class="nav-number">1.6.</span> <span class="nav-text">客户端处理返回的结果数据</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#指令队列"><span class="nav-number">2.</span> <span class="nav-text">指令队列</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#生产者消费者模式"><span class="nav-number">2.1.</span> <span class="nav-text">生产者消费者模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#指令的处理"><span class="nav-number">2.2.</span> <span class="nav-text">指令的处理</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#C-WebBrowser"><span class="nav-number">3.</span> <span class="nav-text">C# WebBrowser</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#获取Form表单，填写输入项"><span class="nav-number">3.1.</span> <span class="nav-text">获取Form表单，填写输入项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#提交表单"><span class="nav-number">3.2.</span> <span class="nav-text">提交表单</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#WinIO"><span class="nav-number">4.</span> <span class="nav-text">WinIO</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#工具代码"><span class="nav-number">5.</span> <span class="nav-text">工具代码</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#JAVA-int型与byte-array的相互转换"><span class="nav-number">5.1.</span> <span class="nav-text">JAVA int型与byte array的相互转换</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#获取浏览器Cookie"><span class="nav-number">5.2.</span> <span class="nav-text">获取浏览器Cookie</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#获取HTML中的img图像"><span class="nav-number">5.3.</span> <span class="nav-text">获取HTML中的img图像</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#C-中字符串和字节数组的转换"><span class="nav-number">5.4.</span> <span class="nav-text">C#中字符串和字节数组的转换</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">
     
      <a href="mailto:chrisrc@qq.com">chrisrc</a> 
    
  </span>
  <span class="author"> &nbsp; QQ: 58122705 </span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"chrisrc"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  








  
  

  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
<script>
(function(){
   var src = (document.location.protocol == "http:") ? "http://js.passport.qihucdn.com/11.0.1.js?ed903ab05fbc5fa64d95e4bfbf3d3a04":"https://jspassport.ssl.qhimg.com/11.0.1.js?ed903ab05fbc5fa64d95e4bfbf3d3a04";
   document.write('<script src="' + src + '" id="sozz"><\/script>');
})();
</script>

  


</body>
</html>
